﻿using Abp.Dependency;
using Mall.DomainModel;
using Mall.DomainModel.IRepository;
using Mall.Service;
using Mall.Web.ViewModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Primitives;
using NLog;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;

namespace Mall.Web.Controllers
{
    public class BaseController : Controller
    {
        public static readonly NLog.ILogger _logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 用户Id
        /// </summary>
        public Guid UserId { get; set; }

        /// <summary>
        /// 用户手机号
        /// </summary>
        public string UserPhone { get; set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public string ShipUserName { get; set; }

        /// <summary>
        /// 企业名称
        /// </summary>

        public string UserEnterpriseName { get; set; }

        //[FromServices]
        //protected IShipperUserRepository _userRepository { get; set; }

        //public BaseController(IShipperUserRepository userRepository)
        //{
        //    _userRepository = userRepository;
        //}

        /// <summary>
        /// 控制器中的操作执行之前调用此方法（先执行这个方法 再执行模型验证）
        /// </summary>
        /// <param name="context"></param>
        //public override void OnActionExecuting(ActionExecutingContext context)
        //{
        //    var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
        //    if (!descriptor.MethodInfo.CustomAttributes.Any(x => x.AttributeType == typeof(AllowAnonymousAttribute)))
        //    {
        //        var tokenHeader = HttpContext.Request.Headers["Authorization"];
        //        if (!StringValues.IsNullOrEmpty(tokenHeader))
        //        {
        //            var strToken = tokenHeader.ToString();
        //            if (strToken.Contains("Bearer "))
        //                strToken = strToken.Remove(0, 7);//去除"Bearer "

        //            var jwtHandler = new JwtSecurityTokenHandler();
        //            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(strToken);
        //            var identity = new ClaimsIdentity(jwtToken.Claims);
        //            var principal = new ClaimsPrincipal(identity);
        //            HttpContext.User = principal;

        //            var userId = User.Claims.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.Sid)?.Value;
        //            var userPhone = User.Claims.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.UniqueName)?.Value;

        //            if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(userPhone))
        //            {
        //                throw new Exception(ErrorCode.E10001);
        //            }
        //            UserId = Guid.Parse(userId);
        //            //UserPhone = userPhone;
        //            var userRep = HttpContext.RequestServices.GetService<IShipperUserRepository>();
        //            if (userRep == null) throw new Exception("无法获取用户仓储服务");
        //            //var userRep = ServiceLocator.Services.GetService(typeof(IShipperUserRepository)) as IShipperUserRepository;

        //            var user = userRep.GetAsync(UserId).Result;

        //          //  var user = _userRepository.GetAsync(UserId).Result;

        //            if (user == null || user.IsDeleted) throw new Exception("用户不存在");
        //            if (!user.Enabled) throw new Exception("用户已禁用");
        //            UserPhone = user.Phone;
        //            ShipUserName = user.Name;
        //        }
        //        else
        //        {
        //            throw new Exception(ErrorCode.E10001);
        //        }
        //    }
        //}
        public override async void OnActionExecuting(ActionExecutingContext context)
        {
            var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
            if (!descriptor.MethodInfo.CustomAttributes.Any(x => x.AttributeType == typeof(AllowAnonymousAttribute)))
            {
                var tokenHeader = HttpContext.Request.Headers["Authorization"];
                if (!StringValues.IsNullOrEmpty(tokenHeader))
                {
                    // ... 前面的token解析代码不变 ...

                    var userRep = HttpContext.RequestServices.GetService<IShipperUserRepository>();
                    if (userRep == null) throw new Exception("无法获取用户仓储服务");


                    // var user = await userRep.GetAsync(UserId);

                    ShipperUser user = null;
                    var getUserTask = userRep.GetAsync(UserId);
                    var timeoutTask = Task.Delay(5000); // 5秒超时
                    var completedTask = await Task.WhenAny(getUserTask, timeoutTask);
                    var cts = new CancellationTokenSource();
                    if (completedTask == timeoutTask)
                    {
                        cts.Cancel(); // 主动取消数据库查询
                        context.Result = new ObjectResult("获取用户信息超时")
                        {
                            StatusCode = StatusCodes.Status408RequestTimeout
                        };
                        return;
                    }
                    user = await getUserTask;
                    //var user = userRep.GetAsync(UserId).Result;
                    if (user == null || user.IsDeleted) throw new Exception("用户不存在");
                    if (!user.Enabled) throw new Exception("用户已禁用");
                    UserPhone = user.Phone;
                    ShipUserName = user.Name;

                }
                else
                {
                    throw new Exception(ErrorCode.E10001);
                }
            }
        }


        /// <summary>
        /// 将String转换为Guid
        /// </summary>
        /// <param name="s">需要转换的字符串</param>
        /// <returns>成功则返回转换后的Guid否则返回Null</returns>
        protected Guid? StringToGuid(string s)
        {
            if (string.IsNullOrWhiteSpace(s)) return null;

            if (Guid.TryParse(s, out var guid)) return guid;

            return null;
        }

        /// 将String转换为枚举
        /// </summary>
        /// <param name="enumName">需要转换的字符串</param>
        /// <returns>成功则返回转换后的枚举否则报错</returns>
        protected T ToEnum<T>(string enumName) where T : struct
        {
            T result;
            if (!string.IsNullOrWhiteSpace(enumName))
            {
                if (Enum.TryParse(enumName.Trim(), out result) && Enum.IsDefined(typeof(T), result))
                {
                    return result;
                }
            }
            throw new Exception("将String转换为枚举失败");
        }

        /// <summary>
        /// 从Unix时间戳获取时间
        /// </summary>
        /// <param name="timestamp">Unix时间戳</param>
        protected DateTime GetTimeFromUnixTimestamp(long timestamp)
        {
            var start = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);
            TimeSpan span = new TimeSpan(long.Parse(timestamp + "0000000"));
            return start.Add(span).Add(new TimeSpan(8, 0, 0));
        }

        protected string GetMD5(string encryptString)
        {
            var md5 = MD5.Create();
            var result = md5.ComputeHash(Encoding.UTF8.GetBytes(encryptString));
            var strResult = BitConverter.ToString(result);
            return strResult.Replace("-", "");
        }

        protected string DateTimeToString(DateTime? dt)
        {
            if (dt == null) return "";
            else return dt.Value.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public static long GetCurrentUnixTimestampSeconds()
        {
            // Unix时间戳是从1970年1月1日UTC时间起至现在的秒数
            DateTime epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            long currentUnixTimestampSeconds = (long)(DateTime.UtcNow - epochStart).TotalSeconds;
            return currentUnixTimestampSeconds;
        }

        /// <summary>
        /// 组织关键字
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static string GetKeyword(string phone, string name)
        {
            List<string> keyList = new List<string>();
            keyList.Add(phone);
            if (!string.IsNullOrEmpty(name))
                keyList.Add(name.Replace(" ", ""));
            string kw = PartString(keyList, 500);
            return kw;
        }

        /// <summary>
        /// 简单分词
        /// </summary>
        /// <param name="sl">字串集合</param>
        /// <param name="maxlength">索引字段最大长度</param>
        /// <returns></returns>
        public static string PartString(List<string> sl, int maxlength)
        {
            string result = string.Join(" ", sl);
            List<string> substrlist = new List<string>();
            substrlist.AddRange(sl);
            foreach (var s in sl)
            {
                for (int i = 1; i < s.Length; i++)
                {
                    if (result.Length + s.Length > maxlength)
                    {
                        return result;
                    }
                    var substr = s.Substring(i, s.Length - i);
                    if (!substrlist.Contains(substr))
                    {
                        substrlist.Add(substr);
                        result += " " + substr;
                    }

                }
            }
            return result;
        }
      

        // 调用方式
      
    }
}
